package service

import (
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"user-center/src/common"
	"user-center/src/constant"
	"user-center/src/db"
	"user-center/src/model"
	"user-center/src/model/VO"
	"user-center/src/model/request"
	"user-center/src/model/response"
	"user-center/src/utils"
)

func FriendAdd(ctx *gin.Context, friendId int64, user *model.User) *response.BaseResponse {
	res := &response.BaseResponse{}
	if friendId <= 0 {
		res.ResponseWithError(common.PARAMS_ERROR, "参数错误")
		return res
	}
	if user == nil {
		res.ResponseWithError(common.NOT_LOGIN, "未登录")
		return res
	}
	if user.Id == friendId {
		res.ResponseWithError(common.NULL_ERROR, "添加不了自己")
		return res
	}
	senderFriendInfo := &model.Friend{
		UserId:   user.Id,
		FriendId: friendId,
		Status:   constant.Request,
	}
	receiverFriendInfo := &model.Friend{
		UserId:   friendId,
		FriendId: user.Id,
		Status:   constant.Pending,
	}

	// 开启事务，加入好友必须同时插入下面俩条数据
	tx := db.GetMySQL().Begin()

	if err := tx.Model(model.Friend{}).Where("userId = ?  and friendId = ? and isDelete = 0 ", user.Id, friendId).Error; err != nil {
		res.ResponseWithError(common.SYSTEM_ERROR, "已经是好友了")
		tx.Rollback()
		return res
	}

	if err := tx.Select("userId", "friendId", "status").Create(senderFriendInfo).Error; err != nil {
		res.ResponseWithError(common.SYSTEM_ERROR, "添加失败")
		log.Error("add error", err)
		tx.Rollback()
		return res
	}

	if err := tx.Select("userId", "friendId", "status").Create(receiverFriendInfo).Error; err != nil {
		res.ResponseWithError(common.SYSTEM_ERROR, "添加失败")
		log.Error("add error", err)
		tx.Rollback()
		return res
	}

	tx.Commit()
	message := &request.FriendChatAddRequest{FriendId: friendId, Content: "hello 我是你的新朋友"}
	FriendChatAdd(ctx, message, user)
	res.ResponseWithData("添加成功")
	return res
}

func FriendDelete(ctx *gin.Context, friendId int64, user *model.User) *response.BaseResponse {
	res := &response.BaseResponse{}
	if friendId <= 0 {
		res.ResponseWithError(common.PARAMS_ERROR, "参数错误")
		return res
	}
	if user == nil {
		res.ResponseWithError(common.NOT_LOGIN, "未登录")
		return res
	}

	// 开启事务，删除好友必须同时处理下面俩条数据
	tx := db.GetMySQL().Begin()

	// 更新好友关系：sender -> receiver
	if err := tx.Model(&model.Friend{}).Where("userId = ? AND friendId = ? and isDelete = 0 ", user.Id, friendId).Update("is_delete", 1).Error; err != nil {
		// 更新失败时回滚事务
		tx.Rollback()
		res.ResponseWithError(common.SYSTEM_ERROR, "删除好友失败")
		return res
	}

	// 更新好友关系：receiver -> sender
	if err := tx.Model(&model.Friend{}).Where("userId = ? AND friendId = ? and isDelete = 0  ", friendId, user.Id).Update("is_delete", 1).Error; err != nil {
		// 更新失败时回滚事务
		tx.Rollback()
		res.ResponseWithError(common.SYSTEM_ERROR, "删除好友失败")
		return res
	}
	tx.Commit()

	res.ResponseWithData("删除成功")
	return res
}

func FriendChatAdd(ctx *gin.Context, req *request.FriendChatAddRequest, user *model.User) *response.BaseResponse {
	res := &response.BaseResponse{}
	if req == nil {
		res.ResponseWithError(common.PARAMS_ERROR, "参数错误")
		return res
	}
	if user == nil {
		res.ResponseWithError(common.NOT_LOGIN, "未登录")
		return res
	}
	// todo 检查是否为好友
	message := model.ChatFriend{
		SenderUserId:   user.Id,
		ReceiverUserId: req.FriendId,
		Content:        req.Content,
	}
	if err := db.GetMySQL().Model(&model.ChatFriend{}).Select("senderUserId", "receiverUserId", "content").Create(&message).Error; err != nil {
		log.Warningf("Create user fail:%v", err)
		res.ResponseWithError(common.SYSTEM_ERROR, "数据库添加消息失败")
		return res
	}
	res.ResponseWithData("发送成功")
	return res
}

func ListFriends(ctx *gin.Context, pageNum, pageSize int, user *model.User) *response.BaseResponse {
	res := &response.BaseResponse{}
	if user == nil {
		res.ResponseWithError(common.NOT_LOGIN, "未登录")
		return res
	}
	//todo 添加
	if pageNum <= 0 {
		pageNum = 1
	}
	if pageSize <= 0 {
		pageSize = 20
	}

	var chatFriends []model.ChatFriend

	sql := `
	SELECT cf.id, cf.senderUserId, cf.receiverUserId, cf.content, cf.createTime
	FROM chatFriend cf
	INNER JOIN (
	    SELECT 
	        CASE 
	            WHEN senderUserId = ? THEN receiverUserId 
	            ELSE senderUserId 
	        END AS user,
	        MAX(createTime) AS max_sent_time
	    FROM chatFriend
	    WHERE  isDelete = 0 and (senderUserId = ? OR receiverUserId = ?)
	    GROUP BY user
	    ORDER BY max_sent_time DESC
-- 	    LIMIT 20
	) latest ON 
	    ((cf.senderUserId = ? AND cf.receiverUserId = latest.user) OR (cf.receiverUserId = ? AND cf.senderUserId = latest.user))
	    AND cf.createTime = latest.max_sent_time
	ORDER BY cf.createTime DESC;
	`

	if err := db.GetMySQL().Raw(sql, user.Id, user.Id, user.Id, user.Id, user.Id).Scan(&chatFriends).Error; err != nil {
		log.Fatalf("failed to execute query: %v", err)
		res.ResponseWithError(common.SYSTEM_ERROR, "获取失败")
		return res
	}

	// 构建 senderId 和 receiverId 切片
	var userIDs []int64
	for _, chatFriend := range chatFriends {
		userIDs = append(userIDs, chatFriend.SenderUserId, chatFriend.ReceiverUserId)
	}

	// 去重 userIDs 切片中的元素
	userIDs = utils.Unique(userIDs)

	// 查询 user 表中的具体信息 todo 待优化
	var users []model.User
	if err := db.GetMySQL().Where("id IN (?) and isDelete = 0 ", userIDs).Find(&users).Error; err != nil {
		log.Fatalf("failed to query users: %v", err)
		res.ResponseWithError(common.SYSTEM_ERROR, "获取失败")
		return res
	}

	var friendChatVOList []VO.FriendChatVO
	for _, i := range chatFriends {
		for _, j := range users {
			if j.Id != user.Id && (i.SenderUserId == j.Id || i.ReceiverUserId == j.Id) {
				f := VO.FriendChatVO{
					SenderUserId:    i.SenderUserId,
					ReceiverUserId:  i.ReceiverUserId,
					MessageId:       i.Id,
					Content:         i.Content,
					CreateTime:      i.CreateTime,
					FriendUsername:  j.Username,
					FriendAvatarUrl: j.AvatarUrl,
				}
				friendChatVOList = append(friendChatVOList, f)
			}
		}
	}
	res.ResponseWithData(friendChatVOList)
	return res
}

func ListHistoryByFriend(ctx *gin.Context, pageNum, pageSize int, friendId int64) *response.BaseResponse {
	res := &response.BaseResponse{}
	//todo 添加
	if pageNum <= 0 {
		pageNum = 1
	}
	if pageSize <= 0 {
		pageSize = 20
	}

	user := GetUserCurrentInfo(ctx)
	if user == nil {
		res.ResponseWithError(common.NOT_LOGIN, "未登录")
		return res
	}
	if friendId <= 0 {
		res.ResponseWithError(common.PARAMS_ERROR, "参数错误")
		return res
	}
	var friendChatVO []VO.FriendChatVO
	var chatFriendList []model.ChatFriend

	if err := db.GetMySQL().Model(&model.ChatFriend{}).Where("isDelete = 0 and ( (senderUserId = ? and receiverUserId = ?) or (senderUserId = ? and receiverUserId = ?) )", user.Id, friendId, friendId, user.Id).Order("createTime desc").Find(&chatFriendList).Error; err != nil {
		log.Fatalf("failed to query chatFriends: %v", err)
		res.ResponseWithError(common.SYSTEM_ERROR, "获取失败")
		return res
	}
	for _, i := range chatFriendList {
		f := VO.FriendChatVO{
			MessageId:      i.Id,
			SenderUserId:   i.SenderUserId,
			ReceiverUserId: i.ReceiverUserId,
			Content:        i.Content,
			CreateTime:     i.CreateTime,
		}
		friendChatVO = append(friendChatVO, f)
	}
	res.ResponseWithData(friendChatVO)
	return res
}
